package com.sq.goodline.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.goodline.config.JobConfig;
import com.sq.goodline.config.OssConfig;
import com.sq.goodline.dao.AudioDetailDao;
import com.sq.goodline.dao.CallDetailDao;
import com.sq.goodline.dao.po.AudioDetail;
import com.sq.goodline.util.DateUtils;
import com.sq.goodline.util.FileUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class RecToWavService {

	@Resource
    JobConfig jobConfig;
	@Resource
	OssConfig ossConfig;
	@Autowired
	CallDetailDao callDetailDao;
	@Autowired
	AudioDetailDao audioDetailDao;
	@Autowired
	OssService ossService;
	
	/**
	 * 将vos生成的.rec录音文件转换成.wav格式
	 * @throws Exception 
	 */
	public void recToWav() throws Exception {
		QueryWrapper<AudioDetail> qw = new QueryWrapper<>();
		qw.eq("audio_status", -1);//-1 原始rec
		qw.orderByAsc("create_time");//升序排列
		qw.last("LIMIT 50");//最多查*笔
		List<AudioDetail> audioDetailList = audioDetailDao.selectList(qw);
		if(audioDetailList==null) {
			log.debug("无待转换录音");
			return;
		}
		for(AudioDetail detail:audioDetailList) {
			//rec转wav
			if(recToWavOne(detail)) {
				String localFile = jobConfig.getWavLocalPath()+"/"+detail.getFlowno()+".wav";
				File wavFile = new File(localFile);
				//存于oss路径规范：yyyy/MM/dd/flowno_sign.wav
				String mySign = DigestUtils.md5Hex(detail.getFlowno()+ossConfig.getSignSalt());
				String objectName = DateUtils.getDayString(detail.getStarttime(), "yyyy/MM/dd/")+detail.getFlowno()+"_"+mySign+".wav";
				
				//上传oss
				boolean upFlag= ossService.fileUploadOss(wavFile, objectName);
				if(upFlag) {
					log.info("上传成功：{}",objectName);
					detail.setAudioStatus(0);//0  已转wav并上传oss
					String recordFileUrl = "/api/download?flowno="+detail.getFlowno()+"&sign="+mySign;
					detail.setRecordFileUrl(recordFileUrl);
					detail.setRecOssPath(objectName);
					int a = audioDetailDao.updateById(detail);
					log.info("更新AudioDetail完成：{}",a);
					
					boolean del = wavFile.delete();
					log.info("删除本地wav文件：{}",del);
				}
			}
		}
	}
	
	/**
	 * 单笔转换流程
	 * vos录音命名规范如下：
录音文件是 20170116111219-1087_0-1088_0-172.16.5.59-172.16.5.127-331606.rec，
名称解释为：时间-主叫号码_类型（0 为话机、1 为网关）-被叫号码_类型（0 为话机、1 为网关）-主叫IP-被叫IP-话单的flowno值。 
	 * @param detail
	 * @return
	 * @throws Exception 
	 */
	private boolean recToWavOne(AudioDetail detail) throws Exception {
		Date d = new Date();
		d.setTime(detail.getStarttime());//通话起始时间的小时，通常是该笔录音的存放子目录
		
		//rec原始录音保存在：/kunshi1-data/record/yyyyMMdd/HH
		String folderPath = jobConfig.getRecLocalPath()+"/"+DateUtils.formatDate(d,"yyyyMMdd/HH");
		File file = FileUtils.findFileByEnds(folderPath, detail.getFlowno()+".rec");
		
        //如果未找到录音文件，则跨到下1小时再找一遍
        if(file==null) {
        	log.info("未找到对应的.rec录音文件:{},flowno:{}",folderPath,detail.getFlowno());
        	Date d2 = DateUtils.addHours(d, 1);
        	folderPath = jobConfig.getRecLocalPath()+"/"+DateUtils.formatDate(d2,"yyyyMMdd/HH");
        	file = FileUtils.findFileByEnds(folderPath, detail.getFlowno()+".rec");
        }
        
        if(file==null) {
        	log.info("未找到对应的.rec录音文件,flowno:{}",folderPath,detail.getFlowno());
        	return false;
        }else {
        	detail.setRecRecordPath(file.getAbsolutePath());
        	return doShellConvert(file,detail.getFlowno());
        }
	}
	
	/**
	 * 执行单个文件的shell转换
	 * @param cmd
	 * @return
	 * @throws Exception 
	 */
	private boolean doShellConvert(File file,String flowno) throws Exception {
		//转换wav后保存在：/kunshi1-data/wav/flowno.wav
		String wavFileName =jobConfig.getWavLocalPath()+"/"+flowno+".wav";
		String cmd = "/home/kunshi/audiorecord/bin/audioconvert -t wav -i "+file.getAbsolutePath() +" -o "+ wavFileName;
		log.info("执行shell命令：{}",cmd);
		
		// 执行shell命令
        Process process = Runtime.getRuntime().exec(cmd); 
        // 读取命令的输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuffer sb = new StringBuffer(); 
        String line;
        while ((line = reader.readLine()) != null) {
        	sb.append(line);
        }
        // 等待进程结束
        int exitCode = process.waitFor();
        String result = sb.toString(); 
        log.info(result);
        log.info("执行shell转换完成：Exited with code : " + exitCode);
        if(result.contains("success")) {
        	/**shell执行成功，输出信息为：
        	convert /kunshi1-data/record/20250123/11/20250123113022-2025122_0-13701837383_1-111.8.83.219-120.27.142.124-273.rec success.
        	*/
        	log.info("rec转wav成功");
        	return true;
        }else {
        	return false;
        }
	}
}
